package com.senjoeson.androidtv.securitydemo;

import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.os.IBinder;
import android.os.Looper;
import android.util.Log;
import android.widget.Toast;

import java.util.Timer;
import java.util.TimerTask;


public class CheckBackgroundService extends Service {


    private static final String TAG = "CheckBackgroundService";
    public Toast toast;
    public Handler mHandler;

    Timer timer = new Timer();
    public CheckBgroundTask mCheckBgroundTask;

    @Override
    public void onCreate() {
        super.onCreate();
        if (mCheckBgroundTask == null) {
            mCheckBgroundTask = new CheckBgroundTask();
        }
        timer.schedule(mCheckBgroundTask, 1000, 1000);
    }

    public CheckBackgroundService() {
        mHandler = new Handler();
    }


    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }


    public void showToast(final Context context, final String content) {
        if (Looper.myLooper() != Looper.getMainLooper()) {
            mHandler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    toast = Toast.makeText(context, content, Toast.LENGTH_SHORT);
                    toast.show();
                }
            }, 2000);
        } else {
            toast = Toast.makeText(context, content, Toast.LENGTH_SHORT);
            toast.show();
        }
    }

    /**
     * 检测程序是否在后台运行
     */
    private class CheckBgroundTask extends TimerTask {

        private boolean isRun;

        @Override
        public void run() {
            setRun(!CheckSecurityUtils.isAppOnForeground(getApplicationContext()));
            if (isRun) {

                showToast(getApplicationContext(), "程序已经进入后台！");

                Log.d(TAG, "运行时:");
            } else {

                Log.d(TAG, "非运行时:");
                if (toast != null) {
                    toast.cancel();
                }
            }
        }


        private void setRun(boolean run) {
            isRun = run;
        }
    }


    @Override
    public void onDestroy() {
        super.onDestroy();
        if (mHandler != null) {
            mHandler.removeCallbacksAndMessages(null);
            mHandler = null;
        }
        if (mCheckBgroundTask != null) {
            mCheckBgroundTask.cancel();
            mCheckBgroundTask = null;
        }
        if (timer != null) {
            timer.cancel();
            timer = null;
        }
        if (toast != null) {
            toast.cancel();
            toast = null;
        }


    }


}
